﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class CheckOut : System.Web.UI.Page
{
    //private int currentState = -1;
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["KFC_ConnectionString"].ConnectionString);
    SqlCommand com = new SqlCommand();

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!(Session["UserID"] != null || Session["UserName"] != null))
        {
            loadUserRoleForm();
        }
        else if (Session["BillName"] != null)
        {
            loadBillForm();
        }

    }
  
    private void loadUserRoleForm()
    {
        mainCheckOutTable.Controls.Clear();

        HtmlTableRow row2 = new HtmlTableRow();

        HtmlTableCell cell2_1 = new HtmlTableCell();
        Label lbUser = new Label();
        lbUser.Text = "<h2>Have you registered?</h2>";
        cell2_1.Controls.Add(lbUser);
        cell2_1.ColSpan = 2;
        row2.Controls.Add(cell2_1);

        HtmlTableRow row1 = new HtmlTableRow();

        HtmlTableCell cell1_2 = new HtmlTableCell();
        Button btOldUser = new Button();
        btOldUser.Text = "Yes, I have been here";
        btOldUser.Click += new EventHandler(btOldUser_Click);
        cell1_2.Controls.Add(btOldUser);
        row1.Controls.Add(cell1_2);

        HtmlTableCell cell1_1 = new HtmlTableCell();
        Button btNewUser = new Button();
        btNewUser.Text = "No, I don't have a account";
        btNewUser.Click += new EventHandler(btNewUser_Click);
        cell1_1.Controls.Add(btNewUser);
        row1.Controls.Add(cell1_1);

        mainCheckOutTable.Controls.Add(row2);
        mainCheckOutTable.Controls.Add(row1);

        upGrid.DataBind();
    }

    void btNewUser_Click(object sender, EventArgs e)
    {
        mainCheckOutTable.Controls.Clear();
        HtmlTableRow row0 = new HtmlTableRow();

        HtmlTableCell cell0_2 = new HtmlTableCell();
        Panel pn1 = new Panel();
        pn1.Controls.Add(newUserDiv_1);
        newUserDiv_1.Visible = true;
        cell0_2.Controls.Add(pn1);
        row0.Controls.Add(cell0_2);

        mainCheckOutTable.Controls.Add(row0);

        LoadEffect();
        upGrid.Update();
    }

    void btOldUser_Click(object sender, EventArgs e)
    {
        loadLoginForm();
    }

    protected void butNewUserResg_Click(object sender, EventArgs e)
    {
        loadRegisterForm();
    }

    private void loadRegisterForm()
    {
        mainCheckOutTable.Controls.Clear();
        HtmlTableRow row0 = new HtmlTableRow();

        HtmlTableCell cell0_2 = new HtmlTableCell();
        Panel pn1 = new Panel();
        pn1.Controls.Add(registerDiv_1);
        registerDiv_1.Visible = true;
        cell0_2.Controls.Add(pn1);
        row0.Controls.Add(cell0_2);

        mainCheckOutTable.Controls.Add(row0);

        LoadEffect();
        upGrid.Update();
    }

    private void loadLoginForm()
    {
        mainCheckOutTable.Controls.Clear();
        HtmlTableRow row0 = new HtmlTableRow();

        HtmlTableCell cell0_2 = new HtmlTableCell();
        Panel pn1 = new Panel();
        pn1.Controls.Add(loginDiv_1);
        loginDiv_1.Visible = true;
        cell0_2.Controls.Add(pn1);
        row0.Controls.Add(cell0_2);

        mainCheckOutTable.Controls.Add(row0);

        LoadEffect();
        upGrid.Update();
    }

    private void loadBillForm()
    {
        if (Session["UserID"] != null || Session["UserName"] != null)
        {
            txtBillAddress.Text = Session["UserAddress"].ToString();
            txtBillPhone.Text = Session["UserPhone"].ToString();
            txtBillName.Text = Session["UserName"].ToString();
        }

        mainCheckOutTable.Controls.Clear();
        HtmlTableRow row0 = new HtmlTableRow();

        HtmlTableCell cell0_2 = new HtmlTableCell();
        Panel pn1 = new Panel();
        pn1.Controls.Add(billDiv_1);
        billDiv_1.Visible = true;
        cell0_2.Controls.Add(pn1);
        row0.Controls.Add(cell0_2);

        mainCheckOutTable.Controls.Add(row0);
        LoadEffect();
        upGrid.Update();
    }

    private bool checkUserAndPass(string email, string pass)
    {
        com.Connection = con;

        com.CommandText = "SELECT * FROM [User] WHERE Email = @Email AND Pass = @Pass";
        com.Parameters.AddWithValue("Email", email);
        com.Parameters.AddWithValue("Pass", pass);
        
        con.Open();
        SqlDataReader rd = com.ExecuteReader();
        if (rd.Read())
        {
            Session["UserID"] = rd["UserID"];
            Session["UserEmail"] = rd["Email"];
            Session["UserName"] = rd["Name"];
            Session["UserAddress"] = rd["Address"];
            Session["UserPhone"] = rd["Phone"];
            con.Close();
            showMesDiv("Welcome " + Session["UserName"], 2);
            return true;
        }
        else
        {
            con.Close();
            return false;
        }

    }

    protected void butNewUserMoveon_Click(object sender, EventArgs e)
    {
        loadBillForm();
    }

    protected void butLogin_Click(object sender, EventArgs e)
    {
        checLogin();
        LoadEffect();
        upGrid.Update();
    }

    private void checLogin()
    {
        showMesDiv(Request.Form["txtLoginEmail"], 1);

        String temp = Request.Form["txtLoginEmail"];
        String temp2 = txtLoginEmail.Text;

        if (Request.Form["txtLoginEmail"] != null)
        {
            if (checkUserAndPass(Request.Form["txtLoginEmail"], Request.Form["txtLoginPass"]))
            {
                loadBillForm();
            }
            else
            {
                showMesDiv("Email or pass is not correct.", 1);
                loadLoginForm();
            }
        }
    }
    private void showMesDiv(string mess, int type)
    {
        mesDiv.InnerHtml = mess;
        mesDiv.Visible = true;

        switch (type)
        {
            case 1:
                mesDiv.Attributes.Add("class", "ui-state-error");
                break;
            case 2:
                mesDiv.Attributes.Add("class", "ui-state-highlight");
                break;
            default:
                break;
        }

        upGrid.Update();
    }

    private void hideMesDiv()
    {
        mesDiv.Visible = false;
    }

    private void LoadEffect()
    {
        string script = "loadEffect();";
        ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);
    }

    private void ChangeDialogTile(String newTitle)
    {
        string script = "loadEffect();changeDialogTile('" + newTitle + "');";
        ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);
    }


    protected void butSubmitBill_Click(object sender, EventArgs e)
    {
        string name = Request.Form["txtBillName"];
        Session["BillName"] = name;
        string address = Request.Form["txtBillAddress"];
        Session["BillAddress"] = address;
        string phone = Request.Form["txtBillPhone"];
        Session["BillPhone"] = phone;
        string note = Request.Form["txtBillNote"];
        Session["BillNote"] = note;
        int totalSum = 0;

        //Thong tin hoa don
        string content = "";
        content += "Reciver name: <strong>" + name + "</strong><br/>";
        content += "Reciver address: <strong>" + address + "</strong><br/>";
        content += "Reciver phone: <strong>" + phone + "</strong><br/>";
        content += "Note: <p style='border:1px black;'>" + note + "</p><br/>";

        billingInfo.Attributes.Add("style", "text-align:left");
        billingInfo.InnerHtml = content;

        //Load bang sang pham
        Dictionary<Int32, Int32> cart = (Dictionary<Int32, Int32>)Session["Cart"];
        Dictionary<Int32, String> cartImage = (Dictionary<Int32, String>)Session["CartImage"];
        DataTable allFoodTable = ((System.Data.DataView)(Session["FoodListAll"])).Table;

        foreach (KeyValuePair<Int32, Int32> pair in cart)
        {
            DataRow[] result = allFoodTable.Select("FoodID = '" + pair.Key + "'");
            HtmlTableRow row1 = new HtmlTableRow();

            HtmlTableCell cell1_2 = new HtmlTableCell();
            Label lb2 = new Label();
            lb2.Text = pair.Value.ToString();
            cell1_2.Controls.Add(lb2);
            row1.Controls.Add(cell1_2);

            HtmlTableCell cell1_1 = new HtmlTableCell();
            Image img1 = new Image();
            img1.ImageUrl = cartImage[pair.Key];
            img1.Width = 40;
            img1.Height = 40;
            cell1_1.Controls.Add(img1);
            row1.Controls.Add(cell1_1);

            HtmlTableCell cell1_4 = new HtmlTableCell();
            Label lb5 = new Label();
            lb5.Text = result[0]["FoodName"].ToString();
            cell1_4.Controls.Add(lb5);
            row1.Controls.Add(cell1_4);

            HtmlTableCell cell1_3 = new HtmlTableCell();
            cell1_3.Align = "right";
            Label lb1 = new Label();
            int price = Int32.Parse(result[0]["Price"].ToString()) * pair.Value;
            totalSum += price;
            lb1.Text = formatPrice(price);
            cell1_3.Controls.Add(lb1);
            row1.Controls.Add(cell1_3);

            lastTable.Controls.Add(row1);
        }

        //Tong cong gia
        HtmlTableRow row2 = new HtmlTableRow();
        row2.Align = "right";

        HtmlTableCell cell2_1 = new HtmlTableCell();
        cell2_1.ColSpan = 5;
        Label lbSum = new Label();
        lbSum.Text = "Total: <strong>" + formatPrice(totalSum) + "</strong>";
        cell2_1.Controls.Add(lbSum);
        row2.Controls.Add(cell2_1);
        lastTable.Controls.Add(row2);

        Session["BillSum"] = totalSum;

        //Dua bang sang pham ra ngoai
        mainCheckOutTable.Controls.Clear();
        HtmlTableRow row0 = new HtmlTableRow();

        HtmlTableCell cell0_2 = new HtmlTableCell();
        Panel pn1 = new Panel();
        pn1.Controls.Add(confrimDiv_1);
        confrimDiv_1.Visible = true;
        cell0_2.Controls.Add(pn1);
        row0.Controls.Add(cell0_2);

        mainCheckOutTable.Controls.Add(row0);
        LoadEffect();
        upGrid.Update();
    }

    private string formatPrice(int price)
    {
        string stringPrice = price.ToString();
        string moneyUnit = " Đ";
        if (price < 1000)
        {
            return stringPrice + moneyUnit;
        }
        else if (price < 1000000)
        {
            return stringPrice.Substring(0, stringPrice.Length - 3) + "." + stringPrice.Substring(stringPrice.Length - 3) + moneyUnit;
        }
        else if (price < 1000000000)
        {
            return stringPrice.Substring(0, stringPrice.Length - 6) + "." + stringPrice.Substring(stringPrice.Length - 5, stringPrice.Length - 4) + "." + stringPrice.Substring(stringPrice.Length - 3) + moneyUnit;
        }
        else
        {
            return price + moneyUnit;
        }
    }

    /// <summary>
    ///     Nut lenh thuc hien + chua lenh dang ky
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void butReSubmit_Click(object sender, EventArgs e)
    {
        //Insert user to database
        string email = Request.Form["txtReEmail"];
        string pass = Request.Form["txtRePass"];
        string name = Request.Form["txtReName"];
        string address = Request.Form["txtReAddress"];
        string phone = Request.Form["txtRePhone"];

        com.Connection = con;
        com.CommandText = "insertUser";
        com.CommandType = CommandType.StoredProcedure;

        com.Parameters.AddWithValue("@Name", name);
        com.Parameters.AddWithValue("@Pass", pass);
        com.Parameters.AddWithValue("@Email", email);
        com.Parameters.AddWithValue("@Address", address);
        com.Parameters.AddWithValue("@Phone", phone);

        con.Open();
        int temp = com.ExecuteNonQuery();
        con.Close();

        Session["UserEmail"] = email;
        Session["UserName"] = name;
        Session["UserAddress"] = address;
        Session["UserPhone"] = phone;

        loadWelcomeForm();
    }

    private void loadWelcomeForm()
    {
        string mess = "";
        mess += "<h1>";
        mess += "Welcome " + Session["UserName"] + ".<br/>";
        mess += "Thank you joining us.";
        mess += "</h1>";
        showMesDiv(mess, 0);
        mainCheckOutTable.Controls.Clear();

        //System.Threading.Thread.Sleep(5000);
        //loadBillForm();
    }

    protected void butLastCofrim_Click(object sender, EventArgs e)
    {
        insertOrderToDB();
    }

    private void insertOrderToDB()
    {
        ////Insert to database
        //Insert Order

        com.Connection = con;
        com.CommandText = "insertOrder";
        com.CommandType = CommandType.StoredProcedure;

        com.Parameters.AddWithValue("@UserID", Int32.Parse(Session["UserID"].ToString()));
        com.Parameters.AddWithValue("@PromotionID", null);
        com.Parameters.AddWithValue("@Address", Session["BillAddress"].ToString());
        com.Parameters.AddWithValue("@Phone", Session["BillPhone"].ToString());
        com.Parameters.AddWithValue("@EmployeeID", 1);
        com.Parameters.AddWithValue("@Comment", "[" + Session["Billname"].ToString() + "] : " + Session["BillNote"].ToString());
        com.Parameters.AddWithValue("@Confirmed", false);
        com.Parameters.AddWithValue("@Finished", false);
        com.Parameters.AddWithValue("@MoneySum", Session["BillSum"]);

        SqlParameter orderID = new SqlParameter("@OrderID", SqlDbType.Int);
        orderID.Direction = ParameterDirection.Output;
        orderID.Value = 1;
        com.Parameters.Add(orderID);

        con.Open();
        int temp = com.ExecuteNonQuery();
        con.Close();

        //Insert OrderDetails
        Dictionary<Int32, Int32> cart = (Dictionary<Int32, Int32>)Session["Cart"];
        com.Connection = con;
        con.Open();

        foreach (KeyValuePair<Int32, Int32> pair in cart)
        {
            com.CommandText = "insertOrderDetails";
            com.CommandType = CommandType.StoredProcedure;

            com.Parameters.AddWithValue("@OrderID", orderID);
            com.Parameters.AddWithValue("@FoodID", pair.Key);
            com.Parameters.AddWithValue("@Number", pair.Value);
            com.Parameters.AddWithValue("@PromotionPercent", 0);

            int temp2 = com.ExecuteNonQuery();
        }

        con.Close();

        ////Show info
        string mess = "";
        mess += "<h1>";
        mess += "Thank you for purchasing.";
        mess += "</h1>";
        showMesDiv(mess, 0);
        mainCheckOutTable.Controls.Clear();
    }
}